#!/usr/bin/python3
# coding=utf-8
"""
ref：https://blog.csdn.net/bskfnvjtlyzmv867/article/details/79970146

"""
import os
import cv2

VIDEOS_SRC_PATH = "videos"
VIDEO_FORMATS = [".mp4", ".avi"]
FRAMES_SAVE_PATH = "image_data"
RESIZE_WIDTH = 720
RESIZE_HEIGHT = 480
TIME_INTERVAL = 10


def video2frame(need_resize: bool):

    videos = os.listdir(VIDEOS_SRC_PATH)

    def filter_format(x, all_formats):
        if x[-4:] in all_formats:
            return True
        else:
            return False

    videos = filter(lambda x: filter_format(x, VIDEO_FORMATS), videos)

    if videos.__sizeof__ == 0:
        print("the nums of videos quilified is 0")
        return

    if not os.path.exists(FRAMES_SAVE_PATH):
        os.mkdir(FRAMES_SAVE_PATH)

    for each_video in videos:
        print("reading video：", each_video)

        each_video_name = each_video[:-4]
        each_video_save_full_path = os.path.join(FRAMES_SAVE_PATH, each_video_name) + "/"

        if not os.path.exists(each_video_save_full_path):
            os.mkdir(each_video_save_full_path)

        each_video_full_path = os.path.join(VIDEOS_SRC_PATH, each_video)

        cap = cv2.VideoCapture(each_video_full_path)
        frame_index = 0
        frame_count = 0
        if cap.isOpened():
            success = True
        else:
            success = False
            print(f"read {each_video} failed!")

        while(success):
            success, frame = cap.read()
            print(f"---> reading the {frame_index} frame {success}.")

            if frame_index % TIME_INTERVAL == 0 and success:
                if need_resize:
                    frame = cv2.resize(frame, (RESIZE_WIDTH, RESIZE_HEIGHT), interpolation=cv2.INTER_AREA)
                cv2.imwrite(each_video_save_full_path + each_video_name + "_%d.jpg" % frame_index, frame)
                frame_count += 1
            frame_index += 1

        cap.release()


def main():
    video2frame(False)


if __name__ == '__main__':
    main()
